import React, { useMemo } from 'react';
import { Table } from 'antd';
import { BasicTableProps } from '../types/table';
import ToolBar from '../components/ToolBar';
import Container, { ColumnsStateMap } from '../container';
import { genColumnKey } from '../utils';

const BasicTable = <RecordType extends object = any>(
  props: BasicTableProps<RecordType> & {
    columns: any[];
  },
): JSX.Element => {
  const { columns } = props;

  const getToolBarProps = () => {
    return {
      ...props.toolbar,
    };
  };

  const { columnsStateMap, setBasicPropsRef } = Container.useContainer();
  setBasicPropsRef(props);
  // 筛出cloums show 是false不显示的
  const tableColums = useMemo(() => {
    console.log('change 11');
    return columns.filter((item) => {
      const columnKey = genColumnKey(item.key);
      const config = columnsStateMap[columnKey];
      if (config && config.show === false) {
        return false;
      }
      return true;
    });
  }, [columnsStateMap, columns]);

  const getTableProps = () => {
    return {
      ...props,
      columns: tableColums,
    };
  };
  return (
    <div>
      <ToolBar {...getToolBarProps()} />
      <Table {...getTableProps()} />
    </div>
  );
};

const ProviderWarp = (props: any) => {
  const { columns } = props;

  function getColumnsStateMap(): ColumnsStateMap {
    const result: ColumnsStateMap = {};
    Object.entries(columns).forEach((item) => {
      const obj: any = item[1];
      const columnKey = genColumnKey(obj.key);
      if (obj.show === false) {
        return;
      }
      result[columnKey] = {
        show: true,
      };
    });
    return result;
  }

  console.log(props);

  return (
    <Container.Provider
      initialState={{
        columnsStateMap: getColumnsStateMap(),
        onColumnsStateChange: (val) => {
          console.log('onColumnsStateChange');
        },
        ...props,
      }}
    >
      <BasicTable {...props} />
    </Container.Provider>
  );
};

export default ProviderWarp;
